package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User user;
        user = userMapper.findByUserName(username);
        return user;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        // 添加
        userMapper.add(username,md5String);

    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPassword) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPassword),id);
    }

    @Override
    public PageBean<User> list(Integer pageNum, Integer pageSize, String username1, String permission1, String createTime1) {
        // 1、创建PageBean对象
        PageBean<User> pageBean = new PageBean<>();

        // 2、开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);

        // 3、调用mapper查询
        List<User> users = userMapper.list(username1, permission1,createTime1);
        //page中提供了方法，可以获取PageHelper分页查询后 记录总数和当前页数据
        Page<User> page = (Page<User>) users;

        //把数据封装到PageBean中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        /*System.out.println("service:pageBean" + pageBean);
        System.out.println("total:"+page.getTotal());*/
        return pageBean;
    }

    @Override
    public void updatePermission(Integer id, String permission) {
        userMapper.updatePermission(id, permission);
    }

    @Override
    public void delete(Integer id) {
        userMapper.deleteUser(id);
    }
}
